package com.itcncp.wechat.app.mini.controller;
import com.aliyun.oss.model.PutObjectResult;
import com.itcncp.common.base.BaseController;
import com.itcncp.common.model.FileResponse;
import com.itcncp.common.util.DateUtils;
import com.itcncp.common.util.JsonUtils;
import com.itcncp.common.util.MD5Util;
import com.itcncp.common.util.OSSUtils;
import com.itcncp.wechat.app.common.constant.ApiConstant;
import com.itcncp.wechat.app.common.constant.ApiResult;
import com.itcncp.wechat.app.common.constant.ApiResultConstant;
import com.itcncp.wechat.app.rpc.api.UserCustomerInfoService;
import io.swagger.annotations.Api;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author daogee
 */
@Controller
@RequestMapping("/file")
@Api(tags = "OSS文件存储",value = "文件上传", description = "文件上传接口",
		produces = "produces",consumes = "consumes",basePath = "/file")
public class FileController extends BaseController {

	private static final Logger LOGGER = LoggerFactory.getLogger( CallBackController.class);
	 
	
	private static final String LOCAL_PATH = FileController.class.getResource("/").getPath();


	@Autowired
	private UserCustomerInfoService userCustomerInfoService;


	/**
	 * 上传图片到阿里OSS
	 */
	@ResponseBody
	@RequestMapping(value = "/picture", method = RequestMethod.POST)
	public Object upFileImage(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request) {
		
		FileResponse fileRsponse = new FileResponse();
		
		String name = "";
		String prevUrl = "";
		
		if(StringUtils.isNotEmpty(request.getParameter("name"))){
			name = request.getParameter("name");
		}
		if(StringUtils.isNotEmpty(request.getParameter("prevUrl"))){
			prevUrl = request.getParameter("prevUrl");
		}
		
		fileRsponse = executeForOSS(file,prevUrl,name, ApiConstant.ALIYUN_OSS_BUCKETNAME_ITCNCP_IMG
				,ApiConstant.ALIYUN_OSS_BUCKETNAME_ITCNCP_IMG_URL);
		

		Map<String, Object> result = new HashMap<>();
		result.put("path", fileRsponse.getFileName());
		return result;
	}
	
	/**
	 * 上传头像
	 */ 
	@ResponseBody
	@RequestMapping(value = "/headImg", method = RequestMethod.POST)
	public Object headImg( HttpServletRequest request,
						   @RequestParam(value = "file", required = false) MultipartFile file
						   ) {

		FileResponse fileRsponse = new FileResponse();

		String name = "";
		String prevUrl = "";
		
		if(StringUtils.isNotEmpty(request.getParameter("name"))){
			name = request.getParameter("name");
		}
		if(StringUtils.isNotEmpty(request.getParameter("prevUrl"))){
			prevUrl = request.getParameter("prevUrl");
		}
		
		fileRsponse = executeForOSS(file,prevUrl,name, ApiConstant.ALIYUN_OSS_BUCKETNAME_ITCNCP_IMG
				,ApiConstant.ALIYUN_OSS_BUCKETNAME_ITCNCP_IMG_URL);


		Map<String, Object> result = new HashMap<>();
		result.put("path", fileRsponse.getRemotePath());

		return new ApiResult( ApiResultConstant.SUCCESS,result,1);
	}
	
	/**
	 * 上传音频文件
	 */
	@ResponseBody
	@RequestMapping(value = "/voice", method = RequestMethod.POST)
	public Object upFileXhbVoice(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request) {
		
		FileResponse fileRsponse = new FileResponse();
		String name = "";
		String prevUrl = "";
		
		if(StringUtils.isNotEmpty(request.getParameter("name"))){
			name = request.getParameter("name");
		}
		if(StringUtils.isNotEmpty(request.getParameter("prevUrl"))){
			prevUrl = request.getParameter("prevUrl");
		}
		
		fileRsponse = executeForOSS(file, prevUrl, name, ApiConstant.ALIYUN_OSS_BUCKETNAME_ITCNCP_VIDEO
				,ApiConstant.ALIYUN_OSS_BUCKETNAME_ITCNCP_VIDEO_URL);

		Map<String, Object> result = new HashMap<>();
		result.put("path", fileRsponse.getRemotePath());

		return new ApiResult( ApiResultConstant.SUCCESS,result,1);
	}
	 
	/**
	 * 上传车牌相关图片
	 */ 
	@ResponseBody
	@RequestMapping(value = "/plateImg", method = RequestMethod.POST)
	public Object upPlateImg(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request) {


		FileResponse fileRsponse = new FileResponse();
		
		String name = "";
		String prevUrl = "";
		
		if(StringUtils.isNotEmpty(request.getParameter("name"))){
			name = request.getParameter("name");
		}
		if(StringUtils.isNotEmpty(request.getParameter("prevUrl"))){
			prevUrl = request.getParameter("prevUrl");
		}
		
		fileRsponse = executeForOSS(file,prevUrl,name, ApiConstant.ALIYUN_OSS_BUCKETNAME_ITCNCP_IMG_CAR
				,ApiConstant.ALIYUN_OSS_BUCKETNAME_ITCNCP_IMG_CAR_URL);

		Map<String, Object> result = new HashMap<>();
		result.put("path", fileRsponse.getRemotePath());

		return new ApiResult( ApiResultConstant.SUCCESS,result,1);
	}
	
	/**
	 * 上传图片
	 * @param file
	 * @param name 图片名称
	 * @param bucketName
	 * @param remoteUrl
	 * @return
	 */
	private static FileResponse  executeForOSS(MultipartFile file, String prevUrl,
											   String name, String bucketName, String remoteUrl){
		FileResponse fileResponse = new FileResponse();
		String localPath = ""; //本地存储路径 完整
		String fileName = file.getOriginalFilename();
		
		
		// 图片名字不为空，说明上传了头像
		if (!fileName.equals("")) {
			// 截取图片后缀
			String suffix = fileName.substring(fileName.lastIndexOf('.'),fileName.length());
			
			if(StringUtils.isEmpty(name)){
				//将图片名称改为唯一
				fileName = MD5Util.md5(MD5Util.UUID()) + suffix;
			}else{
				fileName = name + suffix;
			}
			
			if(StringUtils.isNotEmpty(prevUrl)){
				fileName = prevUrl+"/"+fileName;
			}
			
			// 组装本地路径
			localPath = LOCAL_PATH + fileName;
			 
			//保存文件
			saveFile(file, localPath);
			
			fileResponse.setFileName(fileName);
			fileResponse.setRemotePath(remoteUrl + fileName);
			fileResponse.setLocalPath(localPath);
			fileResponse.setSuffix(suffix);

			//上传到oss
			try {
				try {
					OSSUtils.uploadFile(localPath, fileName, bucketName);
				} catch (FileNotFoundException e) {
					return null;
				}
			} finally{
				//删除上传后文件
				File fileManage = new File(localPath);
				if (fileManage.isFile() && fileManage.exists()) {  
					fileManage.delete(); 
				} 
			}

		}
		
		return fileResponse;
	}

	/**
	 * 上传图片
	 * @param name 图片名称
	 * @param bucketName
	 * @param remoteUrl
	 * @return
	 */
	private static PutObjectResult  executeForOSSURL(String name, String bucketName, String remoteUrl){
		String fileName = remoteUrl;


		PutObjectResult putObjectResult = null;

		// 图片名字不为空，说明上传了头像
		if (!fileName.equals("")) {
			// 截取图片后缀
			String suffix = fileName.substring(fileName.lastIndexOf('.'),fileName.length());

			if(StringUtils.isEmpty(name)){
				//将图片名称改为唯一
				fileName = MD5Util.md5(MD5Util.UUID()) + suffix;
			}else{
				fileName = name + suffix;
			}

			//上传到oss
			try {
				putObjectResult = OSSUtils.uploadFileURL(remoteUrl, fileName, bucketName);


				System.err.println("上传阿里云"+JsonUtils.toJson(putObjectResult));
			} catch (FileNotFoundException e) {
				return null;
			}

		}

		return putObjectResult;
	}
	
	/**
	 * 返回网络全路径
	 * @param file
	 * @return
	 */
	private static String execute(MultipartFile file){
		 
		String localPath = ""; //本地存储路径 完整
		String webUrl = ""; //网络访问路径 完整
		String fileName = file.getOriginalFilename();
		
		// 图片名字不为空，说明上传了头像
		if (!fileName.equals("")) {
			// 截取图片后缀
			String suffix = fileName.substring(fileName.lastIndexOf('.'),fileName.length());
			
			// 将图片名称改为唯一
			fileName = MD5Util.md5(DateUtils.dateFormatNow(null)) + suffix;

			// 组装本地路径
			localPath = LOCAL_PATH + fileName;
			
			// 组装网络路径
//			webUrl = IP + fileName;
			
			//保存文件
			saveFile(file, localPath);

		}
		
		return webUrl;
	}
	

	/**
	 * 保存文件
	 * @param file
	 * @param filePath
	 */
	private static void saveFile(MultipartFile file, String filePath) {

		File targetFile = new File(filePath);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		try {
			file.transferTo(targetFile);

		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	
 
}
 